from datetime import datetime, timedelta
import calendar
import time
from random import randint


class DateHandler(object):
    @staticmethod
    def day_begin_end(times=None):
        times = datetime.now() if times==None else datetime.strptime(times, "%Y-%m-%d")

        start_time = times.strftime("%Y-%m-%d 00:00:00")
        end_time = times.strftime("%Y-%m-%d 23:59:59")
        return start_time, end_time

    @staticmethod
    def get_last_day(times=None):
        last_date = datetime.now() if times == None else datetime.strptime(times, "%Y-%m-%d")
        last_date = last_date - timedelta(days=1)
        return last_date.strftime("%Y-%m-%d")

    @staticmethod
    def month_begin_end(times=None):
        times = datetime.now() if times==None else datetime.strptime(times, "%Y-%m-%d")

        month_begin = times.strftime("%Y-%m-01 00:00:00")
        wday, mrange = calendar.monthrange(times.year, times.month)
        month_end = "%d-%02d-%02d 23:59:59" % (times.year, times.month, mrange)
        return month_begin, month_end

    @staticmethod
    def year_begin_end(times=None):
        times = datetime.now() if times==None else datetime.strptime(times, "%Y-%m-%d")

        start_time = times.strftime("%Y-01-01 00:00:00")
        end_time = times.strftime("%Y-12-31 23:59:59")
        return start_time, end_time

    @staticmethod
    def today():
        times = datetime.now()
        return times.strftime("%Y-%m-%d")

    @staticmethod
    def now():
        times = datetime.now()
        return times.strftime("%Y-%m-%d %H:%M:%S")

    @staticmethod
    def weekday(times=None):
        times = datetime.now() if times == None else datetime.strptime(times, "%Y-%m-%d %H:%M:%S")
        return times.weekday()

    # 获取一个随机的时间
    @classmethod
    def get_random_time(cls):
        start_time_1 = datetime.strptime("%s 07:00:00" % DateHandler.today(), "%Y-%m-%d %H:%M:%S")
        start_time_2 = datetime.strptime("%s 08:00:00" % DateHandler.today(), "%Y-%m-%d %H:%M:%S")

        end_time_1 = datetime.strptime("%s 09:00:00" % DateHandler.today(), "%Y-%m-%d %H:%M:%S")
        end_time_2 = datetime.strptime("%s 10:00:00" % DateHandler.today(), "%Y-%m-%d %H:%M:%S")

        start_time_1, start_time_2 = time.mktime(start_time_1.timetuple()), time.mktime(start_time_2.timetuple())
        end_time_1, end_time_2 = time.mktime(end_time_1.timetuple()), time.mktime(end_time_2.timetuple())

        random_start_time = datetime.fromtimestamp(randint(start_time_1, start_time_2)).strftime("%Y-%m-%d %H:%M:%S")
        random_end_time = datetime.fromtimestamp(randint(end_time_1, end_time_2)).strftime("%Y-%m-%d %H:%M:%S")

        if random_start_time.__ge__(random_end_time):
            random_start_time, random_end_time = DateHandler.get_random_time()

        return random_start_time, random_end_time

    # 时间戳转换
    @staticmethod
    def date_int2str(timestamp):
        return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")

    # 获取过去前n秒，前n分钟，前n小时，前n天，前n周
    @staticmethod
    def get_forth_time(m, forth_type="minutes"):
        times = datetime.now()
        if forth_type == "seconds":
            forth_time = times - timedelta(seconds=m)
        elif forth_type == "minutes":
            forth_time = times - timedelta(minutes=m)
        elif forth_type == "hours":
            forth_time = times - timedelta(hours=m)
        elif forth_type == "days":
            forth_time = times - timedelta(days=m)
        elif forth_type == "weeks":
            forth_time = times - timedelta(weeks=m)
        else:
            forth_time = times
        return forth_time.strftime("%Y-%m-%d %H:%M:%S")

    # 获取月份起始 或 结束时间
    @staticmethod
    def get_month_start_or_end(times=None, month_type="start"):
        times = datetime.now() if times==None else datetime.strptime(times, "%Y-%m")

        if month_type == "start":
            month_time = "%d-%02d-01 00:00:00" % (times.year, times.month)
        elif month_type == "end":
            wday, mrange = calendar.monthrange(times.year, times.month)
            month_time = "%d-%02d-%02d 23:59:59" % (times.year, times.month, mrange)
        else:
            month_time = ""
        return month_time

    # 判断是否是闰年
    @staticmethod
    def is_leap_year(year):
        is_leap = False
        if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
            is_leap = True
        return is_leap

    # 今天是今年的第几天
    @staticmethod
    def days_today_in_this_year(times=None):
        times = datetime.now() if times==None else datetime.strptime(times, "%Y-%m-%d")
        # 初始化天数
        days = times.day
        # 月份集合
        _30_month = {4, 6, 9, 11}
        _31_month = {1, 3, 5, 7, 8, 10, 12}
        for i in range(1, times.month):
            if i in _30_month:
                days += 30
            elif i in _31_month:
                days += 31
            else:
                days += 28
        # 判断闰年
        if DateHandler.is_leap_year(times.year) and times.month > 2:
            days += 1
        return days

    # 两个时间比较, 结果是秒
    @staticmethod
    def time_diff(start_time, end_time):
        start_time = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
        end_time = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
        return (end_time - start_time).total_seconds()

    @staticmethod
    def delta_week(times=None, delta=0):
        times = datetime.now() if not times else datetime.strptime(times, "%Y-%m-%d")
        week = times.weekday()
        week_start = (times - timedelta(days=week-7*delta)).strftime("%Y-%m-%d 00:00:00")
        week_end = (times + timedelta(days=6-week+7*delta)).strftime("%Y-%m-%d 23:59:59")
        return week_start, week_end


if __name__ == '__main__':
    s = DateHandler().get_last_day("2020-04-1")
    # s = s / 60
    print(s)

    # 过去5天的历史数据
    dates = []
    for i in range(5):
        if i == 0:
            dates.append(DateHandler.today())
        else:
            dates.append(DateHandler.get_last_day(dates[-1]))
    print(dates)
